import re
import json


def escape_backslashes(content: str) -> str:
    # 使用正则表达式替换所有的反斜杠，但保留转义字符
    return re.sub(r"\\(?![nrtbfv](?![a-zA-Z]))", r"\\\\", content)


def _loads(content: str) -> dict:
    try:
        return json.loads(content)
    except json.JSONDecodeError:
        return json.loads(escape_backslashes(content))


def json_loads(content: str) -> dict:
    """用于解析llm发送过来的json数据"""
    if not content:
        return {}
    try:
        return _loads(content)
    except json.decoder.JSONDecodeError as error:
        contents = content[content.find("{") :].split("}")
        for index in range(len(contents), 0, -1):
            content = "}".join(contents[:index]).strip() + "}"
            if not content:
                continue
            try:
                return _loads(content)
            except Exception:
                continue
        raise error
